<template>
    <acceptPreview v-if="isAcceptPreview" :applyId="applyId"></acceptPreview>
    <div v-else class="m-window" v-loading="pageLoading" element-loading-text="数据加载中">
       <el-row class="applyLong-col" type="flex">
            <el-col class="opts-col">
               <el-button type="primary" @click="submit" style="width:120px;" :disabled="!isAllowFinancing">融资</el-button>
            </el-col>
            <el-col v-show="!isAllowFinancing" >
                <span class="hint">提示:{{financingHint}}</span>
            </el-col>
            <el-col :span="23" class="info-table-col">
                <el-form :v-model="applyLongForm" ref="applyLongForm" >
                    <el-form-item>
                       <table class="emphasis-table">
                            <tr>
                                <th>“月有钱”说明</th>
                                <td>最长可融6个月，最短可融1个月</td>
                            </tr>
                            <tr>
                                <th>客服</th>
                                <td>{{applyLongForm.custserviceName}}</td> 
                            </tr>
                             <tr>
                                <th>客服电话</th>
                                <td class="hit">{{applyLongForm.custservicePhone}}</td>
                            </tr>
                            <tr>
                                <th>温馨提示</th>
                                <td>可以先联系客服，了解长融！</td>
                            </tr>
                            <tr>
                                <th><div><span style="color:red">*</span><span>申请融资月数</span></div></th>
                                <td>
                                    <el-dropdown  @command="handleCommand">
                                        <span class="el-dropdown-link">
                                            {{applyLongForm.finLMonth}}个月<i class="el-icon-arrow-down el-icon--right"></i>
                                        </span>
                                        <el-dropdown-menu slot="dropdown">
                                            <el-dropdown-item command="1">1个月</el-dropdown-item>
                                            <el-dropdown-item command="2">2个月</el-dropdown-item>
                                            <el-dropdown-item command="3">3个月</el-dropdown-item>
                                            <el-dropdown-item command="4">4个月</el-dropdown-item>
                                            <el-dropdown-item command="5">5个月</el-dropdown-item>
                                            <el-dropdown-item command="6">6个月</el-dropdown-item>
                                        </el-dropdown-menu>
                                    </el-dropdown>
                                </td>
                            </tr>
                            <tr>
                                <th><div><span style="color:red">*</span><span>申请人</span></div></th>
                                <td>
                                    <el-input v-model="applyLongForm.custUser"  placeholder="输入申请人姓名" maxlength="10"></el-input>
                                </td>
                            </tr>
                            <tr>
                                <th><div><span style="color:red">*</span><span>申请人手机</span></div></th>
                                <td>
                                    <el-input v-model="applyLongForm.custPhone"  placeholder="输入申请人手机号码" @blur.prevent="changePhohe()"  @keyup.native="clearNophone()" maxlength="11"></el-input>
                                </td>
                            </tr>
                            <tr>
                                <th><div><span style="color:red">*</span><span>申请融资金额（元）</span></div></th>
                                <td>
                                    <el-input v-model="applyLongForm.money"  placeholder="输入申请融资金额"   @blur.prevent="changeMoney()"  @keyup.native="clearNoNum()" ></el-input>
                                </td>
                            </tr>
                        </table>
                    </el-form-item>
                </el-form>
            </el-col>
             <div class="m-agTable m-top2 m-bottom historyLog-col">
                <label>融资历史记录</label>
                <ag-grid-vue class="ag-theme-balham ag-table"
                        :gridOptions="applyGridOptions"
                        :columnDefs="applyColumnDefs"
                        :rowData="applyRowData"
                        v-loading="loading"></ag-grid-vue>
                <pagination style="height:1%;" :config="{pageNumberChanged, pageSizeChanged, pageNumber: searchParams.current,justifyContent:'flex-end'}" :total="data.total"></pagination>
            </div>
            <!-- <el-col :span="24" class="historyLog-col">
                <label>融资历史记录</label>
                <div class="m-agTable m-top2 m-bottom">
                    <ag-grid-vue class="ag-theme-balham ag-table"
                            :gridOptions="applyGridOptions"
                            :columnDefs="applyColumnDefs"
                            :rowData="applyRowData"
                            v-loading="loading"></ag-grid-vue>
                    <pagination :config="{pageNumberChanged, pageSizeChanged, pageNumber: searchParams.current}" :total="data.total"></pagination>
               </div>
            </el-col> -->
        </el-row>
    </div>
</template>
<style lang="less" scoped>
    .applyLong-col{
        flex-direction:column;
        height: 100%;
        overflow-y: auto;
        .info-table-col{
            margin-top: 10px;
            .emphasis-table{
                width: 100%;
                margin-top: 10px;
                .hit{
                    color: #409EFF !important;
                }
                .font-underline{
                    text-decoration:underline;
                }
                tr{
                    &:nth-child(even) th,&:nth-child(even) td{
                        background: #F9FAFA;
                    }
                    td,th{
                    border: 1px solid #eee;
                    padding: 0 10px;
                    height: 35px;
                    line-height: 35px;
                    text-align: right;
                    width: 50%;
                    }
                    th{
                        &:first-child{
                            width:10%;
                            text-align:center;
                        }
                        &:last-child{
                            width: 90%;
                        }
                    }
                    td{
                        text-align: left;
                        & /deep/ .el-input__inner{
                            border: none !important;
                            outline-style: none !important;
                            height: 35px;
                            line-height: 35px;
                            margin-left: -10px;
                        }
                    }
                }
            }
        }
        .historyLog-col{
            margin-top: 35px;
            height: calc(100% - 460px);
            min-height: 350px;
           label{
                font-size: 12px;
                font-weight: 600;
            }
            .ag-table{
                 width:100%;
                height:99%;
                margin-top: 8px;
            }
        }
        .hint{
            color: red;
            font-size: 14px;
            font-weight: 600;
            font-family: '黑体';
        } 
    }
</style>
<script>
import gridOptions from "lesso-common/public/gridOptions"
import Pagination from '@/components/pagination.vue'
import AcceptPreview from '@/components/SRM/pageComponents/acceptPreview.vue'
import { mapState,mapActions } from 'vuex'
import constant from "@/public/constant"
import { formatPrice,formatPriceEdit,regainOriginalMoneyFormat } from '@/util/format'

export default {
    data() {
        return {
            pageLoading:true,
            applyId:'',
            isAcceptPreview:false,
            applyLongForm:{
                custserviceId:null,
                custserviceName:'',
                custservicePhone:'',
                custUser:'',
                custPhone:'',
                applyAmt:"",
                money:0,
                finLMonth:1,
                applyUserId:null,
                applyUser:'',
                applyPhone:'',
                custId:'',
                custName:'',
                finType:'1', //融资类型 1长融
            },
            applyGridOptions: {},
            applyColumnDefs: [
            {
                headerName: "序号",
                field: "xuhao",
                valueGetter: 'node.id',
                cellRenderer: function (params) {
                    if (params.value != undefined) {
                        return +params.value + 1;
                    }
                },
                width:100
            },
            {
                headerName: "申请编号",
                field: "itemNo",
                width:200
            },
            {
                headerName: "融资开始日期",
                field: "payDate",
                width:120
            },
            {
                headerName: "融资金额",
                field: "actAmt",
                valueFormatter:params=>{
                    return formatPrice(params.value)
                },
                width:120
            },
            {
                headerName: "已还款金额",
                field: "paybackAmount",
                valueFormatter: params => {
                    return formatPrice(params.value)
                },
                width:120
            },
            {
                headerName: "融资产品",
                field: "finType",
                width:100
            },
            {
                headerName: "还款状态",
                field: "paybackProcessStatus",
                width:100
            }],
            applyRowData: [],
            searchParams:{
                condition:{
                    custId:null
                },
                current:1,
                size:10
            },
            data:{
               total:0 
            },
            loading: false,
            isAllowFinancing:true,
            financingHint:'',
        }
    },
    created() {
        // this.getOneOrSave()
        this.applyGridOptions = gridOptions()
        this.searchParams.condition.custId = this.supplyChainFinance.custInf.custId
        this.applyLongForm.custName = this.supplyChainFinance.custInf.custName
        this.applyLongForm.custId = this.supplyChainFinance.custInf.custId
        this.getHistoryPageList()
        this.getCustomerServiceInfo()
    },
    computed:{
        ...mapState(['supplyChainFinance'])
    },
    methods: {
        ...mapActions(['changeApplyId','changeFromPage']),
        async getHistoryPageList(){
            this.loading = true
            let that = this
            await that.$http.getHistoryPageList(that.searchParams).then(({data})=>{
                that.loading = false
                if(data.code == 200){
                    that.applyRowData = data.rows
                    that.data.total = data.total               
                }else{
                    this.$alert(`获取数据失败：${data.info}`, {
                        confirmButtonText: "确定",
                        customClass: "alertFailure"
                    });
                }
            })
            .catch((error)=>{
                this.$alert("查询历史数据列表失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            })
        },
        async getCustomerServiceInfo(){
            let that = this
            await that.$http.getCustomerServiceInfo().then(({data})=>{
                setTimeout(()=>{
                    that.pageLoading = false
                },500)
                if(data.code == 200){
                    let row = data.rows
                    that.applyLongForm.custserviceId = row.custserviceId
                    that.applyLongForm.custserviceName = row.custserviceName
                    that.applyLongForm.custservicePhone = row.custservicePhone
                    this.applyLongForm.applyUserId = row.custserviceId
                    this.applyLongForm.applyUser = row.custserviceName
                    this.applyLongForm.applyPhone = row.custservicePhone
                }else{
                    this.$alert(`获取数据失败：${data.info}`, {
                        confirmButtonText: "确定",
                        customClass: "alertFailure"
                    });
                }
            })
            .catch((error)=>{
                this.pageLoading = false
                this.$alert("查询失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            }) 
        },
        async confirmApply(){
            let that = this
             const loading = this.$loading({
                    lock: true,
                    text: '融资申请提交中，请稍等',
                    spinner: 'el-icon-loading',
                    background: 'rgba(255,255,255,.9)'
                })
            await that.$http.confirmApply(that.applyLongForm).then(({data})=>{
                that.loading = false
                loading.close();
                if(data.code == 200){
                    this.$alert('操作成功！', {
                        confirmButtonText: "确定",
                        customClass: "alertSuccess",
                        callback:function(){
                            that.isAcceptPreview = true
                            that.applyId = data.rows.id
                        }
                    })
                    that.changeFromPage('applyLong')
                }else{
                    this.$alert(data.info, {
                        confirmButtonText: "确定",
                        customClass: "alertFailure"
                    });
                }
            })
            .catch((error)=>{
                this.$alert("查询失败，请检查网络！", {
                    confirmButtonText: "确定",
                    customClass: "alertFailure"
                })
            }) 
        },
        //获取客户表详情,若没有则新增
        // async getOneOrSave(){
        //     let params = this.supplyChainFinance.custInf2
        //     let that = this
        //     await this.$http.getOneOrSave(params).then(({data})=>{
        //         if(data.code == 200 && data.rows){
        //             console.log('融资状态:0-未融资,1-在天进宝  2-在长融:',data.rows.finStatus)
        //             //'融资状态:0-未融资,1-在天进宝  2-在长融'
        //             //that.isAllowFinancing = data.rows.finStatus > 1 ? false:true
        //             that.financingHint = data.rows.finStatus == 1?'您已申请了天进宝，暂不可申请长融': data.rows.finStatus == 2? '您长融的金额尚未还清，暂不可再申请':''
        //         }       
        //     })
        //     .catch((errror)=>{
        //         this.$alert("查询客户表，请检查网络！", {
        //         confirmButtonText: "确定",
        //         customClass: "alertFailure"
        //         })
        //     })
        // },
        handleCommand(command){
            this.applyLongForm.finLMonth = command
        },
        pageNumberChanged(pageNumber){
            this.searchParams.current = pageNumber
            this.getHistoryPageList()
        },
        pageSizeChanged(pageSize){
            this.searchParams.current = 1
            this.searchParams.size = pageSize
            this.getHistoryPageList()
        },
        submit(){
            if(!this.applyLongForm.custUser){
                this.$alert("提示：请输入申请人姓名", {
                    confirmButtonText: "确定",
                    customClass: "alertPrompt"
                })
                return
            }
            if(!this.applyLongForm.custPhone){
                this.$alert("提示：请输入申请人手机号码", {
                    confirmButtonText: "确定",
                    customClass: "alertPrompt"
                })
                return
            }
            if(!this.applyLongForm.money){
                this.$alert("提示：请输入申请融资金额", {
                    confirmButtonText: "确定",
                    customClass: "alertPrompt"
                })
                return
            }
            if(Number(this.applyLongForm.applyAmt) < 10000){
                this.$alert("提示：申请融资金额不得低于一万元", {
                    confirmButtonText: "确定",
                    customClass: "alertPrompt"
                })
                return
            }

             this.$confirm("确认申请融资？")
                .then(_ => {
                    this.confirmApply()
                })
        },
        //输入框填写电话校验
        changePhohe(){
            if(this.applyLongForm.custPhone==''){
                return
            }
             // var patt = /^(13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147)\d{8}$/;
            var patt = /^[1][3,4,5,6,7,8,9][0-9]{9}$/;
            var Result = patt.test(this.applyLongForm.custPhone);
            if(!Result){
                this.$alert("请输入正确手机号码", {
                    confirmButtonText: "确定",
                    customClass: "alertPrompt"
                })
                this.applyLongForm.custPhone=""
                return false;
            }
        }, 
        changeMoney(){
            this.applyLongForm.applyAmt=regainOriginalMoneyFormat(this.applyLongForm.money);
            //  if( (Number(this.applyLongForm.applyAmt)<10000&&this.applyLongForm.applyAmt!=="0")){
            //     showAlert({
            //         msg: '融资金额不得低于一万元',
            //         type: 0
            //     })
            //     this.applyLongForm.money="0";
            // }
            const nums = this.applyLongForm.money.toString().split('.')
            if(this.applyLongForm.money!==''){
                if(nums.length == 1){
                    this.applyLongForm.money = this.applyLongForm.money+'.00'
                }
                else if(nums[1].length == 1){
                    this.applyLongForm.money = this.applyLongForm.money+'0'
                }
            }
        }, 
        //只允许输入两位小数，并实时转换为千分位
       clearNoNum(){ 
           if(typeof  this.applyLongForm.money=='string'){ 
                this.applyLongForm.money = this.applyLongForm.money.replace(/[^(\d|.)]/g,"");//只允许输入数字
                this.applyLongForm.money = this.applyLongForm.money.replace(/\.{2,}/g,"."); //只保留第一个. 清除多余的   
                this.applyLongForm.money = this.applyLongForm.money.replace(".","$#$").replace(/\./g,"").replace("$#$",".");  
                this.applyLongForm.money = this.applyLongForm.money.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能输入两个小数   
                this.applyLongForm.money = formatPriceEdit(this.applyLongForm.money.toString().replace(/[,]/g,''))
            }  
        },
        clearNophone(){ 
           if(typeof  this.applyLongForm.custPhone=='string'){ 
                this.applyLongForm.custPhone = this.applyLongForm.custPhone.replace(/[^\d]/g,"");//只允许输入数字
            }  
        }      
    },
    components:{
        Pagination,
        AcceptPreview
    }
}
</script>


